package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class DelayMessageListener {

    private final IOrderService orderService;
    private final PayClient payClient;

    /**
     * 监听延迟消息
     * @param orderId
     */

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        log.info("收到延迟消息：{}",orderId);
        //1.根据id查询订单
        Order order = orderService.getById(orderId);

        //2.对订单进行判断
        if (order == null || order.getStatus() != 1){
            return;
        }
        //3.根据订单id去支付服务查询支付单
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        //4.对支付单进行判断
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3){
            //4.1 已支付，将订单标志为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            //4.2 未支付，取消订单，并且恢复库存
            orderService.cancelOrder(orderId);
        }



    }
}
